<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票财务分析数据列表</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    
    <style>
        .table th, .table td {
            text-align: center;
            vertical-align: middle;
        }
        .btn-group {
            margin-bottom: 20px;
        }
        .loading {
            text-align: center;
            padding: 50px;
            font-size: 18px;
            color: #666;
        }
        .success-message {
            color: #28a745;
        }
        .error-message {
            color: #dc3545;
        }
        .stat-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
        .stat-label {
            color: #666;
            font-size: 14px;
        }
        .pe-low {
            color: #28a745;
        }
        .pe-medium {
            color: #ffc107;
        }
        .pe-high {
            color: #dc3545;
        }
        .roe-low {
            color: #dc3545;
        }
        .roe-medium {
            color: #ffc107;
        }
        .roe-high {
            color: #28a745;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 class="mt-5 mb-4">股票财务分析数据管理</h1>
    
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-value" id="totalCount">0</div>
                <div class="stat-label">股票总数</div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-value" id="avgPE">0.00</div>
                <div class="stat-label">平均市盈率(TTM)</div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-value" id="avgROE">0.00%</div>
                <div class="stat-label">平均ROE(TTM)</div>
            </div>
        </div>
    </div>
    
    <div class="btn-group">
        <button class="btn btn-primary" id="fetchDataBtn">
            <i class="fas fa-sync-alt"></i> 手动抓取数据
        </button>
        <a href="/stockpe/statistics" class="btn btn-info">
            <i class="fas fa-chart-bar"></i> 数据统计分析
        </a>
    </div>
    
    <div class="mt-3" id="message"></div>
    
    <div class="loading" id="loading">
        <i class="fas fa-spinner fa-spin"></i> 加载中...
    </div>
    
    <table id="stockPETable" class="table table-striped table-bordered" style="display: none;">
        <thead>
            <tr>
                <th>序号</th>
                <th>股票代码</th>
                <th>股票名称</th>
                <th>交易日期</th>
                <th>市盈率(TTM)</th>
                <th>ROE(TTM)</th>
                <th>ROE季度环比</th>
                <th>ROE年度环比</th>
                <th>更新时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

<!-- 详情模态框 -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailModalLabel">股票财务详情</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="detailContent" class="container">
                    <!-- 详情内容将动态填充 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // 初始化DataTable
        const table = $('#stockPETable').DataTable({
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.13.4/i18n/zh-CN.json"
            },
            "columns": [
                {"data": null, "orderable": false, "defaultContent": ""},
                {"data": "securityCode"},
                {"data": "securityName"},
                {"data": "tradeDate"},
                {"data": "peTTM"},
                {"data": "roeTTM"},
                {"data": "roeTTMQuarterly"},
                {"data": "roeTTMYearly"},
                {"data": "updateTime"},
                {"data": null, "orderable": false, "defaultContent": "<button class='btn btn-sm btn-info view-detail'>查看详情</button>"}
            ],
            "createdRow": function(row, data, dataIndex) {
                // 设置PE样式
                const peCell = $(row).find('td:eq(4)');
                const peValue = parseFloat(data.peTTM);
                if (peValue > 0) {
                    if (peValue < 10) {
                        peCell.addClass('pe-low');
                    } else if (peValue < 30) {
                        peCell.addClass('pe-medium');
                    } else {
                        peCell.addClass('pe-high');
                    }
                }
                
                // 设置ROE样式
                const roeCell = $(row).find('td:eq(5)');
                const roeValue = parseFloat(data.roeTTM);
                if (roeValue < 0) {
                    roeCell.addClass('roe-low');
                } else if (roeValue < 15) {
                    roeCell.addClass('roe-medium');
                } else {
                    roeCell.addClass('roe-high');
                }
                roeCell.text(roeValue + '%');
                
                // 设置ROE季度环比样式
                const roeQuarterlyCell = $(row).find('td:eq(6)');
                const roeQuarterlyValue = parseFloat(data.roeTTMQuarterly);
                if (roeQuarterlyValue > 1) {
                    roeQuarterlyCell.addClass('text-success');
                } else {
                    roeQuarterlyCell.addClass('text-danger');
                }
                roeQuarterlyCell.text(roeQuarterlyValue.toFixed(2));
                
                // 设置ROE年度环比样式
                const roeYearlyCell = $(row).find('td:eq(7)');
                const roeYearlyValue = parseFloat(data.roeTTMYearly);
                if (roeYearlyValue > 1) {
                    roeYearlyCell.addClass('text-success');
                } else {
                    roeYearlyCell.addClass('text-danger');
                }
                roeYearlyCell.text(roeYearlyValue.toFixed(2));
            }
        });
        
        // 行号处理
        table.on('order.dt search.dt', function() {
            table.column(0, {search:'applied', order:'applied'}).nodes().each(function(cell, i) {
                cell.innerHTML = i + 1;
            });
        }).draw();
        
        // 加载数据
        loadData();
        
        // 手动抓取数据按钮点击事件
        $('#fetchDataBtn').click(function() {
            $(this).attr('disabled', true);
            $('#message').html('<div class="alert alert-info">数据抓取中，请稍候...</div>');
            
            $.ajax({
                url: '/stockpe/fetchData',
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        $('#message').html('<div class="alert alert-success">' + response.message + '</div>');
                        // 重新加载数据
                        loadData();
                    } else {
                        $('#message').html('<div class="alert alert-danger">' + response.message + '</div>');
                    }
                    $('#fetchDataBtn').attr('disabled', false);
                },
                error: function() {
                    $('#message').html('<div class="alert alert-danger">数据抓取失败，请稍后重试</div>');
                    $('#fetchDataBtn').attr('disabled', false);
                }
            });
        });
        
        // 查看详情按钮点击事件
        $('#stockPETable').on('click', '.view-detail', function() {
            const rowData = table.row($(this).parents('tr')).data();
            loadDetail(rowData.securityCode);
        });
    });
    
    // 加载数据列表
    function loadData() {
        $.ajax({
            url: '/stockpe/dataList',
            type: 'GET',
            success: function(data) {
                $('#stockPETable').DataTable().clear().rows.add(data).draw();
                $('#loading').hide();
                $('#stockPETable').show();
                
                // 更新统计信息
                updateStatistics(data);
            },
            error: function() {
                $('#message').html('<div class="alert alert-danger">数据加载失败，请稍后重试</div>');
                $('#loading').hide();
            }
        });
    }
    
    // 加载详情
    function loadDetail(code) {
        $.ajax({
            url: '/stockpe/detail/' + code,
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    let detailHtml = generateDetailHtml(data);
                    $('#detailContent').html(detailHtml);
                    $('#detailModal').modal('show');
                } else {
                    alert(response.message);
                }
            },
            error: function() {
                alert('加载详情失败，请稍后重试');
            }
        });
    }
    
    // 生成详情HTML
    function generateDetailHtml(data) {
        let html = `
        <div class="row mb-4">
            <div class="col-md-12">
                <h3>${data.securityName} (${data.securityCode})</h3>
                <p>交易日期：${formatDate(data.tradeDate)} | 更新时间：${formatDate(data.updateTime)}</p>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">核心财务指标</div>
                    <div class="card-body">
                        <table class="table table-hover">
                            <tbody>
                                <tr>
                                    <td>市盈率(TTM)</td>
                                    <td class="${getPEClass(data.peTTM)}">${data.peTTM}</td>
                                </tr>
                                <tr>
                                    <td>ROE(TTM)</td>
                                    <td class="${getROEClass(data.roeTTM)}">${data.roeTTM}%</td>
                                </tr>
                                <tr>
                                    <td>ROE季度环比</td>
                                    <td class="${data.roeTTMQuarterly > 1 ? 'text-success' : 'text-danger'}">${data.roeTTMQuarterly}</td>
                                </tr>
                                <tr>
                                    <td>ROE年度环比</td>
                                    <td class="${data.roeTTMYearly > 1 ? 'text-success' : 'text-danger'}">${data.roeTTMYearly}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">ROE趋势分析</div>
                    <div class="card-body">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>季度</th>
                                    <th>ROE(%)</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
        
        // 添加8个季度的ROE数据
        const quarters = [
            {rate: data.roeLast1Rate, date: data.roeLast1Date},
            {rate: data.roeLast2Rate, date: data.roeLast2Date},
            {rate: data.roeLast3Rate, date: data.roeLast3Date},
            {rate: data.roeLast4Rate, date: data.roeLast4Date},
            {rate: data.roeLast5Rate, date: data.roeLast5Date},
            {rate: data.roeLast6Rate, date: data.roeLast6Date},
            {rate: data.roeLast7Rate, date: data.roeLast7Date},
            {rate: data.roeLast8Rate, date: data.roeLast8Date}
        ];
        
        quarters.forEach(quarter => {
            if (quarter.rate && quarter.date) {
                html += `
                <tr>
                    <td>${quarter.date}</td>
                    <td>${quarter.rate}</td>
                </tr>
                `;
            }
        });
        
        html += `
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        `;
        
        return html;
    }
    
    // 更新统计信息
    function updateStatistics(data) {
        $('#totalCount').text(data.length);
        
        // 计算平均PE和ROE
        let peSum = 0, roeSum = 0;
        let peCount = 0, roeCount = 0;
        
        data.forEach(item => {
            if (item.peTTM && parseFloat(item.peTTM) > 0) {
                peSum += parseFloat(item.peTTM);
                peCount++;
            }
            if (item.roeTTM) {
                roeSum += parseFloat(item.roeTTM);
                roeCount++;
            }
        });
        
        const avgPE = peCount > 0 ? (peSum / peCount).toFixed(2) : '0.00';
        const avgROE = roeCount > 0 ? (roeSum / roeCount).toFixed(2) : '0.00';
        
        $('#avgPE').text(avgPE);
        $('#avgROE').text(avgROE + '%');
    }
    
    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }
    
    // 获取PE样式类
    function getPEClass(pe) {
        pe = parseFloat(pe);
        if (pe < 10) return 'text-success';
        if (pe < 30) return 'text-warning';
        return 'text-danger';
    }
    
    // 获取ROE样式类
    function getROEClass(roe) {
        roe = parseFloat(roe);
        if (roe < 0) return 'text-danger';
        if (roe < 15) return 'text-warning';
        return 'text-success';
    }
</script>
</body>
</html>